package com.android.fragmentdemo.definenestedscroll
import android.content.Context
import android.util.AttributeSet
import android.view.MotionEvent
import android.view.ViewConfiguration
import android.webkit.WebView
import androidx.core.view.ViewCompat
import kotlin.math.abs

class NetScrollWebView @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null) : WebView(context, attrs) {
    private val mScrollOffset = IntArray(2)
    private val mScrollConsumed = IntArray(2)
    private val mTouchSlop = ViewConfiguration.get(context).scaledTouchSlop

    private var mLastY: Float = 0f
    private var dragIng: Boolean = false

    init {
        isNestedScrollingEnabled = true
    }

    override fun dispatchTouchEvent(ev: MotionEvent?): Boolean {
        when (ev?.action) {
            MotionEvent.ACTION_MOVE -> {
                if (abs(ev.rawY - mLastY) > mTouchSlop) {
                    dragIng = true
                } else {
                    super.dispatchTouchEvent(ev)
                }
                if (dragIng) {
                    if (parent != null) {
                        parent.requestDisallowInterceptTouchEvent(true)
                    }
                    //主动调用dispatchNestedPreScroll，请求父容器处理
                    dispatchNestedPreScroll(
                        0,
                        (mLastY - ev.rawY).toInt(),
                        mScrollConsumed,
                        mScrollOffset)
                    mLastY = ev.rawY
                }
            }
            MotionEvent.ACTION_DOWN -> {
                dragIng = false
                super.dispatchTouchEvent(ev)
                //startNestedScroll启动嵌套滑动
                startNestedScroll(ViewCompat.SCROLL_AXIS_VERTICAL)
                mScrollConsumed[1] = 0
                mLastY = ev.rawY
            }
            MotionEvent.ACTION_UP -> {
                stopNestedScroll()
            }
            else -> {
                super.dispatchTouchEvent(ev)
            }
        }
        return true
    }

    //强制自己不消费move
    override fun onTouchEvent(ev: MotionEvent?): Boolean {
        performClick()
        if (dragIng || ev?.action == MotionEvent.ACTION_MOVE) {
            return false
        }
        return super.onTouchEvent(ev)
    }

    override fun performClick(): Boolean {
        return super.performClick()
    }
}